<script setup lang="ts">
import { ElRow, ElCol, ElCard, ElSkeleton } from 'element-plus'
import { Echart } from '@/components/Echart'
import { pieOptions, barOptions, lineOptions } from './echarts-data'
import { ref, reactive, unref } from 'vue'
import { getTreeDepartmentsApi } from '@/api/department'
import { GetCheckViewApi } from '@/api/assessment'
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { Table, TableColumn } from '@/components/Table'
const { t } = useI18n()

const loading = ref(true)
const columns: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'depName',
    label: t('userDemo.department')
  },
  {
    field: 'totalCount',
    label: '上传数量'
  },

  {
    field: 'checkTotalCount',
    label: '抽查数量'
  },
  {
    field: 'passCount',
    label: '通过数量'
  },
  {
    field: 'passRate',
    label: '通过率'
  }
]
const departmentList = ref([])
const fetchDepartment = async () => {
  const res = await getTreeDepartmentsApi({})
  departmentList.value = res.data
}
fetchDepartment()
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'depGuid',
    label: t('userDemo.department'),
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'guid',
      props: {
        label: 'depName',
        value: 'guid',
        children: 'children'
      },
      placeholder: '请选择部门',
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true,
      defaultExpandAll: true,
      filterable: true
    },
    optionApi: async () => {
      return departmentList.value || []
    }
  },

  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])
const searchParams = ref({})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getAllApi()
}
const handleColors = () => {
  let color = ''
  let r = Math.floor(Math.random() * 256)
  let g = Math.floor(Math.random() * 256)
  let b = Math.floor(Math.random() * 256)
  color = `rgb(${r},${g},${b})`
  return color
}
const colorHex = (string) => {
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  if (/^(rgb|RGB)/.test(string)) {
    var aColor = string.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',')
    var strHex = '#'
    for (var i = 0; i < aColor.length; i++) {
      var hex = Number(aColor[i]).toString(16)
      if (hex === '0') {
        hex += hex
      }
      strHex += hex
    }
    if (strHex.length !== 7) {
      strHex = string
    }
    return strHex
  } else if (reg.test(string)) {
    var aNum = string.replace(/#/, '').split('')
    if (aNum.length === 6) {
      return string
    } else if (aNum.length === 3) {
      var numHex = '#'
      for (var i = 0; i < aNum.length; i += 1) {
        numHex += aNum[i] + aNum[i]
      }
      return numHex
    }
  } else {
    return string
  }
}
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption
const dataList = ref([])
const getAllApi = async () => {
  const res = await GetCheckViewApi({ ...unref(searchParams) })

  if (res) {
    dataList.value = res.data
    set(
      pieOptionsData,
      'legend.data',
      res.data.map((v) => t(v.depName))
    )
    pieOptionsData!.series![0].data = res.data.map((v) => {
      return {
        name: t(v.depName),
        value: v.passRate
        // itemStyle: { color: colorHex(handleColors()) }
      }
    })
    set(
      barOptionsData,
      'xAxis.data',
      res.data.map((v) => t(v.depName))
    )
    set(barOptionsData, 'series', [
      {
        name: '上传数量',
        data: res.data.map((v) => v.totalCount),
        type: 'bar'
      },
      {
        name: '抽查数量',
        data: res.data.map((v) => v.checkTotalCount),
        type: 'bar'
      },
      {
        name: '通过数量',
        data: res.data.map((v) => v.passCount),
        type: 'bar'
      }
    ])
    loading.value = false
  }
}

getAllApi()
</script>

<template>
  <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
  <ElRow :gutter="20" justify="space-between">
    <ElCol :xl="14" :lg="14" :md="24" :sm="24" :xs="24">
      <ElCard shadow="hover" class="mb-20px">
        <ElSkeleton :loading="loading" animated>
          <Echart :options="barOptionsData" :height="300" />
        </ElSkeleton>
      </ElCard>
    </ElCol>
    <ElCol :xl="10" :lg="10" :md="24" :sm="24" :xs="24">
      <ElCard shadow="hover" class="mb-20px">
        <ElSkeleton :loading="loading" animated>
          <Echart :options="pieOptionsData" :height="300" />
        </ElSkeleton>
      </ElCard>
    </ElCol>
    <ElCol :span="24">
      <Table :columns="columns" :data="dataList" :loading="loading" />
    </ElCol>
  </ElRow>
</template>
